package com.wq.httpclientcore.event;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wq.httpclientcore.entities.po.ApiConfig;
import com.wq.httpclientcore.service.ApiConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;

@Component
public class AuthConfigDeletedEventListener {

    @Autowired
    private ApiConfigService apiConfigService;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) // 事务提交后触发
    public void handleAuthConfigDeletedEvent(AuthConfigDeletedEvent event) {
        List<Long> authConfigIds = event.getAuthConfigIds();
        
        LambdaQueryWrapper<ApiConfig> queryWrapper = Wrappers.lambdaQuery(ApiConfig.class);
        queryWrapper.in(ApiConfig::getAuthConfigId, authConfigIds);
        List<ApiConfig> queryConfigs = apiConfigService.list(queryWrapper);

        for (ApiConfig queryConfig : queryConfigs) {
            queryConfig.setAuthConfigId(null);
        }

        if (!queryConfigs.isEmpty()) {
            apiConfigService.updateBatchById(queryConfigs);
        }
    }
}